import {resolve} from "path";
import {generateConfig, getCmdParams, getDirName, promisify, rmDirFile} from './utils.mjs'
import fs from "fs";

const __dirname = getDirName(import.meta.url)

function delDist () {
    console.log('正在删除dist文件夹')
    const distOut = resolve(__dirname, '../dist')
    const errInfo = rmDirFile(distOut)
    console.log(errInfo ? '删除失败，原因：' + errInfo : '删除完成')
}

function delPages () {
    console.log('正在删除 pages 文件夹')
    const path = resolve(__dirname, '../pages')
    const errInfo = rmDirFile(path)
    console.log(errInfo ? '删除失败，原因：' + errInfo : '删除完成')
}

;(async () => {
    // 生成配置文件
    await generateConfig()

    try {
        // 删除dist
        // 先打包完再删除 dist
        delDist()
    } catch (err) {
        console.log(err)
    }
    // 打包
    console.log('正在打包...')
    const cmdParams = getCmdParams('--base') || '/'
    const build = `npx vitepress build docs --base ${cmdParams}`
    const buildRes = await promisify(build, '打包')
    if (buildRes) {
        // 删除 pages
        delPages()

        // 移动 dist 到 pages
        const newDir = resolve(__dirname, '../pages/')
        const oldDir = resolve(__dirname, '../dist/')
        fs.cpSync(oldDir, newDir, {
            recursive: true
        })
        console.log('构建完成')

        // 删除 dist
        delDist()
    }
})()